<template>
    <el-card shadow="never" class="index">
        <template #header>
            <div class="card_header">
                <b>老师管理</b>
            </div>
        </template>
        <el-card class="box-card" shadow="never">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="教师名">
                    <el-input v-model="formInline.name" placeholder="教师名"></el-input>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="formInline.phone" placeholder="手机号"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="formInline.email" placeholder="邮箱"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 内容区 -->
        <el-table stripe ref="multipleTableRef" v-loading="loading" :data="filterTableData" style="width: 100%;"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" sortable label="序号" width="60" />
            <el-table-column label="头像" width="60" prop="address">
                <template #default="scope">
                    <el-image :src="'http://localhost:5199' + scope.row.avatar_url" fit="fill">
                        <template #error>
                            <div class="image-slot">
                                <el-icon>
                                    <icon-picture />
                                </el-icon>
                            </div>
                        </template>
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column label="编号" prop="username" width="120"></el-table-column>
            <el-table-column label="名称" prop="name" width="120"></el-table-column>
            <el-table-column label="班级" prop="cls" width="120"></el-table-column>
            <el-table-column label="手机号" sortable prop="phone" width="120" />
            <el-table-column label="邮箱" sortable prop="email"  width="160"/>
            <el-table-column label="地址" sortable prop="address" />
            <el-table-column align="center" label="操作">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin-top: 20px">
            <el-pagination background hide-on-single-page :current-page="pageNum" :page-size="pageSize"
                :total="totalNum" @current-change="handlePageChange" layout="prev, pager, next"
                style="margin-bottom:10px;"></el-pagination>
            <el-button type="danger" @click="handleSelectDelete">删除</el-button>
            <el-button type="primary" @click="handleAdd">添加</el-button>
        </div>
        <!-- 内容去 end -->
    </el-card>
</template>

<script>
import { reactive, ref, computed, onBeforeMount, toRaw, getCurrentInstance } from 'vue'
import { ElTable } from 'element-plus'
import { Picture as IconPicture } from '@element-plus/icons'
import { teacherService } from '../../interfaces/service'
import router from '../../router';


export default {
    components: { IconPicture, ElTable },
    setup() {
        const { proxy } = getCurrentInstance()

        // 钩子函数
        onBeforeMount(() => {
            loadTalbeData()
        })

        const loadTalbeData = () => {
            let data = {
                "pageSize": pageSize.value,
                "pageNum": pageNum.value,
            };
            var formInlineCondition = toRaw(formInline);
            Object.keys(formInlineCondition).forEach(key => {
                if (formInlineCondition[key]) {
                    data[`conditions[${key}]`] = formInlineCondition[key]
                }
            });
            loading.value = true
            teacherService.getTeachers(data)
                .then(res => {
                    loading.value = false
                    if (res.success) {
                        let list = res.data.list
                        let total_num = res.data.totalNum
                        totalNum.value = total_num
                        tableData.value = list
                    }
                })
        }

        const delConfig = [
            "确定删除?",
            "提示",
            {
                confirmButtonText: '删除',
                confirmButtonClass: "del-confirm-button",
                cancelButtonText: '取消',
                type: 'error',
                draggable: true
            }
        ]

        // do not use same name with ref
        const formInline = reactive({
            name: '',
            phone: '',
            email: '',
        })

        // 处理搜索按钮
        const handleSearch = () => {
            loadTalbeData()
        }

        // 多选删除
        const handleSelectDelete = (raw) => {
            if (multipleSelection.value && multipleSelection.value.length > 0) {
                ElMessageBox.confirm(...delConfig).then(() => {
                    let ids = '';
                    multipleSelection.value.forEach(item => {
                        ids += item.id + ','
                    });
                    teacherService.delTeachers({ id: ids })
                        .then(res => {
                            if (res.code === 0) {
                                ElMessage.success("删除成功")
                                loadTalbeData()
                            }
                        })
                })
            } else {
                ElMessage.info("请先选中一行数据")
            }
        }

        // 添加学生
        const handleAdd = () => {
            router.push({ name: "TeacherAdd" })
        }

        // 表格加载状态
        const loading = ref(false)
        //表格引用
        const multipleTableRef = ref(null)
        // 表格选中的数据
        const multipleSelection = ref(null)

        // 表格改变事件
        const handleSelectionChange = (val) => {
            // 表格选中的数据
            multipleSelection.value = val
        }

        // 过滤标签
        // const filterTag = (value, row) => {
        //     return row.tag === value
        // }

        // 表格数据
        const tableData = ref([])

        // 本地搜索条件
        const search = ref('')
        const filterTableData = computed(() =>
            tableData.value.filter(
                (data) =>
                    !search.value || data.name.toLowerCase().includes(search.value.toLowerCase())
            )
        )

        // 编辑
        const handleEdit = (index, row) => {
            router.replace({ name: 'TeacherUpdate', params: { id: row.id } })
            // router.push({ name: "TeacherUpdate" })
        }

        // 删除
        const handleDelete = (index, row) => {
            if (index >= 0) {
                ElMessageBox.confirm(...delConfig).then(() => {
                    teacherService.delTeachers({ id: row.id })
                        .then(res => {
                            if (res.success) {
                                filterTableData.value.splice(index, 1)
                                ElMessage.success("删除成功")
                            }
                        })
                })
            }
            console.log(index, row)
        }

        // 分页组件
        const pageNum = ref(1)
        const pageSize = ref(10)
        const totalNum = ref(10)
        // 当前页改变事件
        const handlePageChange = (n) => {
            pageNum.value = n
            loadTalbeData()
        }

        return {
            formInline,
            loading,
            multipleSelection,
            multipleTableRef,
            pageNum,
            pageSize,
            totalNum,
            filterTableData,
            handleSearch,
            // filterTag,
            handleEdit,
            handleAdd,
            handleDelete,
            handleSelectDelete,
            handleSelectionChange,
            handlePageChange,
        }
    }
}
</script>

<style lang="scss" scoped>
.card_header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.box-card {
    margin-bottom: 50px;
}
</style>
